select ro.id id, ro.house_details_id houseDetailsId,
        ro.external_id externalId, hd.phone phone, hd.part part,
        hd.tel_numbers telNumbers, hd.zone_square zoneSquare, hd.house_square houseSquare,
        hd.level level, hd.address address, hd.gas gas, hd.adv_info advInfo, hd.rooms rooms,
        p.state state, p.date date, p.price_value priceValue, hd.sewerage sewerage, hd.water water,
          (select if(p.price_value=sp.price_value,0,if(p.price_value>sp.price_value,1,-1))
                  from price sp
                  where
                      sp.realty_object_id = ro.id
                      and
                       sp.date < p.date
              order by sp.date desc limit 1
          ) dynamic

from realty_object ro
    join house_details hd on hd.id = ro.house_details_id
    join price p on p.realty_object_id = ro.id
    where p.date = (
        select max(sp.date)
            from price sp, realty_object sro
        where sro.id = sp.realty_object_id and sro.house_details_id is not null)
    and p.state in (${displayWithStates})
order by p.state desc, ro.external_id asc
